package drone.basis.express ;

import java.util.Map ;

import com.googlecode.aviator.runtime.function.AbstractFunction ;
import com.googlecode.aviator.runtime.function.FunctionUtils ;
import com.googlecode.aviator.runtime.type.AviatorDouble ;
import com.googlecode.aviator.runtime.type.AviatorObject ;

import drone.basis.util.HexUtil ;

public class FuncGetBit extends AbstractFunction
{

	@Override
	public AviatorObject call (
			Map < String , Object > env ,
			AviatorObject arg1 ,
			AviatorObject arg2
	)
	{
		byte u8 = FunctionUtils.getNumberValue ( arg1 , env ).byteValue ( ) ;
		int index = FunctionUtils.getNumberValue ( arg2 , env ).intValue ( ) ;

		if ( index > 7 || index < 0 )
		{
			try
			{
				throw new Exception ( "invaild index" ) ;
			} catch ( Exception e )
			{
				System.out.print ( HexUtil.byte2Hex ( u8 ) + " invaild index : " + index ) ;
			}
		}

		long tmp ;
		if ( ( ( u8 & 0xff ) & ( 0x1 << index ) ) > 0 )
		{
			tmp = 1 ;
		} else
		{
			tmp = 0 ;
		}

		return new AviatorDouble ( ( double ) ( tmp ) ) ;
	}

	public String getName ( )
	{
		return "getbit" ;
	}
}
